﻿using System;
using System.Collections.Generic;
using System.Text;
using Forecast.Database;

namespace Forecast.Business
{
    internal class FavouriteStock
    {
        private IDictionary<int, int> _overview;
        private IList<Prediction> _allActivePredictions;
        private Prediction _favouritePrediction;
        private Player _player;
        private const int MIN_NUMBER_STOCKS = 50;

        internal FavouriteStock(Player player, IList<Prediction> allActivePredictions) 
        {
            _player = player;
            _allActivePredictions = allActivePredictions;
        }

        internal string GetFavourite(
            IList<Holding> allHoldings, 
            IList<Offer> allActiveOffers)
        {
            PrepareCounting(_allActivePredictions);
            LoopHoldings(allHoldings);
            LoopOffers(allActiveOffers);
            LoopForFavouriteStock();
            if (_favouritePrediction == null)
                return "None";
            return _favouritePrediction.Ticker;
        }

        private void LoopForFavouriteStock()
        {
            int maxCount = 0;
            int maxCountPredictionId = -1;
            foreach (int key in _overview.Keys)
            {
                int count = _overview[key];
                if (count > maxCount && count > MIN_NUMBER_STOCKS)
                {
                    maxCount = count;
                    maxCountPredictionId = key;
                }
            }
            SetFavouritePrediction(maxCountPredictionId);
        }

        private void SetFavouritePrediction(int predictionId)
        {
            foreach (Prediction prediction in _allActivePredictions)
            {
                if (prediction.Id != predictionId)
                    continue;
                _favouritePrediction = prediction;
                break;
            }
        }

        private void LoopOffers(IList<Offer> allActiveOffers)
        {
            foreach (Offer offer in allActiveOffers)
            {
                if (offer.PlayerId != _player.Id)
                    continue;
                if (offer.IsBuy)
                    continue;
                _overview[offer.PredictionId] += offer.NumPredictions;
            }
        }

        private void LoopHoldings(IList<Holding> allHoldings)
        {
            foreach (Holding holding in allHoldings)
            {
                if (holding.PlayerId != _player.Id)
                    continue;
                _overview[holding.PredictionId] += holding.NumPredictions;
            }
        }

        private void PrepareCounting(IList<Prediction> allActivePredictions)
        {
            _overview = new Dictionary<int, int>();
            foreach (Prediction prediction in allActivePredictions)
            {
                _overview.Add(prediction.Id, 0);
            }
        }
    }
}
